import React, { useState } from 'react';
import { Card, Spin, Button, Form, message, Select } from 'antd';
import { useMount } from 'react-use';
import moment from 'moment';

import { BottomAction } from '@/components';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { premiumBaseService } from '@/services/salaryManage/salaryCalculate';
import { insuranceHousingFundService } from '@/services/salaryManage/salaryCalculateService';
import { withRoutePage } from '@/utils/enhanceUtils';
import { isSuccess } from '@/utils/request';
import pageTabUtil from '@/utils/pageTabUtil';
import LimitInput from '@/components/LimitInput';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import { getAreaItemPath } from '@/pages/SalaryManage/components/CityCascader';
import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';
import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';

const { Item } = Form;

const { getSocial, updateSocial } = premiumBaseService;

const numberOption = (name, max = 1000000000) => ({
    validateFirst: true,
    rules: [
        {
            required: true,
            message: `请填写【${name}】`
        },
        {
            type: 'number',
            min: 0,
            message: `【${name}】不能小于0`
        },
        {
            type: 'number',
            max,
            message: `【${name}】不能超过${max}`
        },
        {
            type: 'number',
            message: `【${name}】输入长度不能大于12`
        },
        {
            validator: (rule, value, callback) => {
                const dotPosition = String(value).indexOf('.');
                // 小数位数超过8位时
                if (
                    dotPosition > 0 &&
                    String(value).length > dotPosition + 1 &&
                    String(value).substr(dotPosition + 1).length > 8
                ) {
                    callback(new Error());
                } else {
                    callback();
                }
            },
            message: '小数位数不能超过8位'
        }
    ]
});

const wrapperPageModel = pageModel => {
    const { year, month, kpiStartYear, kpiStartMonth, kpiEndYear, kpiEndMonth, ...rel } = pageModel;
    // 所属月份
    if (year && month) {
        rel.v_period = moment(`${year}-${(month < 10 ? '0' : '') + month}`);
    }

    // 开始区间
    if (kpiStartYear && kpiStartMonth) {
        rel.v_kpiStart = moment(`${kpiStartYear}-${(kpiStartMonth < 10 ? '0' : '') + kpiStartMonth}`);
    }

    // 结束区间
    if (kpiEndYear && kpiEndMonth) {
        rel.v_kpiEnd = moment(`${kpiEndYear}-${(kpiEndMonth < 10 ? '0' : '') + kpiEndMonth}`);
    }

    return rel;
};

const getPostData = (pageModel, formValue) => {
    const { socialCityCode, ...otherFormValue } = formValue;
    const rel = { ...pageModel, ...otherFormValue };
    const cityArr = getAreaItemPath(socialCityCode);
    const inx = cityArr.length - 1;
    rel.socialCityName = cityArr[inx].nameZh;

    return rel;
};

const PremiumBaseEdit = ({ form, location }) => {
    const [loading, setLoading] = useState(false);
    const [pageModel, setPageModel] = useState({});
    const [cityList, setCityList] = useState([]);
    const { getFieldDecorator } = form;

    const { id } = location.query;

    // 取消
    const onCancel = () => pageTabUtil.closeTab();

    // 保存
    const onSave = () => {
        form.validateFieldsAndScroll((errors, values) => {
            if (errors) {
                return;
            }

            const postData = getPostData(pageModel, values);
            setLoading(true);
            updateSocial(postData)
                .then(response => {
                    setLoading(false);
                    if (!isSuccess(response)) {
                        message.error(`编辑失败：${response.msg}`);
                        return;
                    }
                    message.success('保存成功！');
                    tabMessageUtil.noticeFromRefresh();
                    pageTabUtil.closeTab();
                })
                .catch(() => {
                    setLoading(false);
                });
        });
    };

    useMount(async () => {
        setLoading(true);
        try {
            const pageModelResponse = await getSocial({ id });
            setLoading(false);

            if (isSuccess(pageModelResponse)) {
                const responseModel = wrapperPageModel(pageModelResponse.data);
                setPageModel(responseModel);
                const cityResponse = await insuranceHousingFundService.querySocialCityList(
                    responseModel.organizationCode,
                    0
                );

                if (isSuccess(cityResponse)) {
                    setCityList(cityResponse.data);
                } else {
                    message.error(cityResponse.msg);
                }
            } else {
                message.error(pageModelResponse.msg);
            }
        } catch (e) {
            setLoading(false);
        }
    });

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={pageModel.organizationCode}>
                <Card bordered={false} title="编辑险金基数">
                    <Spin spinning={loading}>
                        <Form
                            layout="horizontal"
                            labelCol={{ span: 5 }}
                            wrapperCol={{ span: 19 }}
                            style={{ maxWidth: '630px' }}
                        >
                            <Item label="行政机构">
                                <OrganizationNameConnect organizationCode={pageModel?.organizationCode} />
                            </Item>
                            <Item label="姓名">
                                <span style={{ whiteSpace: 'nowrap' }}>
                                    {pageModel?.employeeNo} {pageModel?.employeeName}
                                </span>
                            </Item>
                            <Item label="所属城市：">
                                <div style={{ width: '220px' }}>
                                    {getFieldDecorator('socialCityCode', {
                                        initialValue: pageModel?.socialCityCode
                                    })(
                                        <Select placeholder="请选择">
                                            {cityList.map(enumItem => (
                                                <Select.Option
                                                    key={enumItem.socialCityCode}
                                                    value={enumItem.socialCityCode}
                                                    title={enumItem.socialCityNamePath}
                                                >
                                                    {enumItem.socialCityNamePath}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    )}
                                </div>
                            </Item>
                            <Item label="户籍类型">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('housePlace', {
                                        initialValue: pageModel?.housePlace
                                    })(
                                        <Select placeholder="请选择">
                                            {Object.entries(pageModel?.housePlaceMap || {}).map(enumItem => (
                                                <Select.Option key={enumItem[0]} value={Number(enumItem[0])}>
                                                    {enumItem[1]}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    )}
                                </div>
                            </Item>
                            <Item label="初始月薪">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptBaseSalaryAmt', {
                                        initialValue: pageModel?.encryptBaseSalaryAmt,
                                        ...numberOption('初始月薪')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="初始月绩效">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptKpiMonthAmt', {
                                        initialValue: pageModel?.encryptKpiMonthAmt,
                                        ...numberOption('初始月绩效')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="养老保险">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptOldBaseAmt', {
                                        initialValue: pageModel?.encryptOldBaseAmt,
                                        ...numberOption('养老保险')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="失业保险">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptUnemployBaseAmt', {
                                        initialValue: pageModel?.encryptUnemployBaseAmt,
                                        ...numberOption('失业保险')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="医疗保险">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptHospitalBaseAmt', {
                                        initialValue: pageModel?.encryptHospitalBaseAmt,
                                        ...numberOption('医疗保险')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="大病保险">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptIllBaseAmt', {
                                        initialValue: pageModel?.encryptIllBaseAmt,
                                        ...numberOption('大病保险')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="公积金">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptFundBaseAmt', {
                                        initialValue: pageModel?.encryptFundBaseAmt,
                                        ...numberOption('公积金')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="生育保险">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptBirthBaseAmt', {
                                        initialValue: pageModel?.encryptBirthBaseAmt,
                                        ...numberOption('生育保险')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="工伤保险">
                                <div style={{ width: '145px' }}>
                                    {getFieldDecorator('encryptHarmBaseAmt', {
                                        initialValue: pageModel?.encryptHarmBaseAmt,
                                        ...numberOption('工伤保险')
                                    })(<NumberSettingInput thousandsSeparator="," maxLength={15} />)}
                                </div>
                            </Item>
                            <Item label="补充说明">
                                {getFieldDecorator('remark', {
                                    initialValue: pageModel?.remark
                                })(<LimitInput maxLength={200} area showNumber rows={3} placeholder="补充说明..." />)}
                            </Item>
                        </Form>
                        <BottomAction>
                            <Button onClick={onCancel}>取消</Button>
                            <Button type="primary" onClick={onSave}>
                                确定
                            </Button>
                        </BottomAction>
                    </Spin>
                </Card>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(Form.create()(PremiumBaseEdit));
